package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.barcodescandemo.ScannerInerface;
import com.example.administrator.k3xiangmu.adapter.LXAdapter;
import com.example.administrator.k3xiangmu.adapter.RukuAdapter;
import com.example.administrator.k3xiangmu.entity.CK;
import com.example.administrator.k3xiangmu.entity.RukuEntity;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class LxActivity extends AppCompatActivity {
    private Toolbar toolbar;
    ProgressDialog dialog;
    private String number="";
    private String name="";
    private LXAdapter adapter;
    private Button bt;
    private String number2="";
    ListView lv;
    private List<RukuEntity> list=new ArrayList<>();
    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    private double total = 0;
    private TextView tvnumber;
    private String ckid = "";
    private String ckname = "";
    ScannerInerface Controll = new ScannerInerface(this);
    private List<CK> listCK = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lx);
        EventBus.getDefault().register(this);
        Controll.open();
        Controll.setOutputMode(1);//使用广播模式
        mFilter = new IntentFilter("android.intent.action.SCANRESULT");
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 此处获取扫描结果信息
                final String scanResult = intent.getStringExtra("value");
                Toast.makeText(LxActivity.this, "解析结果:" + scanResult, Toast.LENGTH_LONG).show();
                number=scanResult;
                getName();
            }
        };

        dialog = new ProgressDialog(this);
        setTool();
        setView();
        setListen();

    }
    private void setListen(){
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(list.size()==0){
                    Toast.makeText(LxActivity.this, "订单不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    UpdateTextTask3 updateTextTask = new UpdateTextTask3(LxActivity.this);
                    updateTextTask.execute();
                }
            }
        });
    }
    private void setView(){
        tvnumber = (TextView) findViewById(R.id.number);
        lv = (ListView) findViewById(R.id.lv);
        bt=(Button)findViewById(R.id.tj);
        adapter=new LXAdapter(list,this);
        lv.setAdapter(adapter);
    }
    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("零星单");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String msg = "";
                switch (item.getItemId()) {
                    case R.id.action_sm:
                        msg += "Click edit";
                        break;

                }

                if (!msg.equals("")) {
                    Toast.makeText(LxActivity.this, msg, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LxActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, 111);

                }
                return true;

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);//加载menu文件到布局
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 111) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    number=result;
                    getName();

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(LxActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void getName() {
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(this);
        updateTextTask.execute();
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            if(!name.equals("")){
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.dialog3, null);
                final EditText et1 = (EditText) layout.findViewById(R.id.et1);


                et1.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

                Button bt=(Button)layout.findViewById(R.id.bt_ck);
                final TextView tv=(TextView)layout.findViewById(R.id.tv_ck);
                bt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        final String[] items = { "大棚","大棚卖出","大棚损耗","花店","花店卖出","花店损耗","回收" };
//                        AlertDialog.Builder listDialog =
//                                new AlertDialog.Builder(LxActivity.this);
//                        listDialog.setTitle("选择仓库");
//                        listDialog.setItems(items, new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                // which 下标从0开始
//                                // ...To-do
//
//                                tv.setText(items[which]);
//                            }
//                        });
//                        listDialog.show();
                        getCK((Button) v);
                    }
                });


                new AlertDialog.Builder(LxActivity.this).setTitle("请完成订单").setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        double s1 =Double.parseDouble(et1.getText().toString())  ;

                        String s3=tv.getText().toString()+"";

//                        if (s1.equals("")) {
//                            Toast.makeText(LxActivity.this, "数量不能为空", Toast.LENGTH_LONG).show();
//                            return;
//                        }

//                        if(s3.equals("")){
//                            Toast.makeText(LxActivity.this, "仓库为空", Toast.LENGTH_LONG).show();
//                            return;
//                        }

                        RukuEntity e = new RukuEntity();
                        e.setNumber((int)s1);
                        e.setName(name);
                        e.setId(number2);
                        e.setCkid(ckid);
                        e.setCkname(ckname);
//

                    //
                        double t =(e.getNumber());
                        for (RukuEntity en : list) {
                            if (en.getId().equals(e.getId())) {


                                total += t;

                                tvnumber.setText(total + "");
                                en.setPrice(e.getPrice());
                                en.setNumber(e.getNumber() +en.getNumber());
                                en.setCkid(e.getCkid());
                                en.setCkname(ckname);
                                adapter.notifyDataSetChanged();


                                return;
                            }
                        }
                        total += t;
                        tvnumber.setText(total + "");
                        list.add(e);
                        adapter.notifyDataSetChanged();


                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
            }else {
                name="";
                number="";
                number2="";
            }

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
    class UpdateTextTask3 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask3(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection3(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();

            Toast.makeText(LxActivity.this, "提交成功", Toast.LENGTH_LONG).show();
            //lear();
            adapter.notifyDataSetChanged();
        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {

            String sql = "select * from t_icitem where FNumber='"+number+"'";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                name= rs.getString("FName");
                number2=rs.getString("FItemID");

            }



            rs.close();
            stmt.close();
        } catch (SQLException e) {

            Log.i("ssss",e.toString());
            Toast.makeText(LxActivity.this,"连接数据库失败",Toast.LENGTH_LONG).show();


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
    public void testConnection3(Connection con) throws java.sql.SQLException {
        CallableStatement callStmt = null;
        CallableStatement callStmt2 = null;

        try {
//            callStmt=con.prepareCall("{call [xp_lx] (?,?,?)}");
//            callStmt2=con.prepareCall("{call [xp_lx2] (?,?,?)}");
//            for(int i=0;i<list.size();i++){
//                if(i==0){
//                    callStmt.setString(1,list.get(i).getId());
//                    callStmt.setString(2,list.get(i).getNumber());
//                    callStmt.setString(3,"885");
//
//                    callStmt.execute();
//                }else {
//                    callStmt2.setString(1,list.get(i).getId());
//                    callStmt2.setString(2,list.get(i).getNumber());
//                    callStmt2.setString(3,"885");
//
//                    callStmt2.execute();
//                }
//            }
//
//            callStmt3=con.prepareCall("{call [x_icstockbii_29] (?)}");
//            callStmt3.setString(1,"1135");
//            callStmt3.execute();
            callStmt=con.prepareCall("{call [x_chuku] (?,?,?,?)}");
            callStmt2=con.prepareCall("{call [x_chuku2] (?,?,?,?)}");
            for(int i=0;i<list.size();i++){
                if(i==0){
//                    callStmt.setString(1,list.get(i).getId());
//                    callStmt.setString(2,list.get(i).getNumber());
//                    callStmt.setString(3,"885");
//
//                    callStmt.execute();
                    callStmt.setString(1,list.get(i).getName());
                    callStmt.setString(2,list.get(i).getNumber()+"");
                    callStmt.setString(3,list.get(i).getPrice());
                    callStmt.setString(4,list.get(i).getCkid());

                    callStmt.execute();
                }else {
                    callStmt2.setString(1,list.get(i).getName());
                    callStmt2.setString(2,list.get(i).getNumber()+"");
                    callStmt2.setString(3,list.get(i).getPrice());
                    callStmt2.setString(4,list.get(i).getCkid());

                    callStmt2.execute();
                }
            }

//            callStmt3=con.prepareCall("{call [x_icstockbii_29] (?)}");
//            callStmt3.setString(1,"1135");
//            callStmt3.execute();





        } catch (SQLException e) {



        } finally {
            if (null != callStmt) {
                callStmt.close();
                callStmt2.close();

            }
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
    private BroadcastReceiver MsgReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            System.out.print(action);
            //android.intent.action.SCANRESULT
            if (action.equals("android.intent.action.SCANRESULT")){
                String mMsg = intent.getStringExtra("value");



                    Toast.makeText(LxActivity.this, "解析结果:" + mMsg, Toast.LENGTH_LONG).show();
                    number=mMsg;
                    getName();



            }

        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    protected void onPause() {
        // 注销获取扫描结果的广播
        this.unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mReceiver = null;
        mFilter = null;

        Controll.close();

        super.onDestroy();
    }
    private void getCK(Button v) {
        UpdateTextTask4 updateTextTask = new UpdateTextTask4(this, v);
        updateTextTask.execute();

    }
    class UpdateTextTask4 extends AsyncTask<Void, Integer, Integer> {
        private Context context;
        private Button v;

        UpdateTextTask4(Context context, Button v) {
            this.context = context;
            this.v = v;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection4(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            if (listCK.size() > 0) {
                final String[] s = new String[listCK.size()];
                for (int i = 0; i < listCK.size(); i++) {
                    s[i] = listCK.get(i).getFName();
                }
                AlertDialog ad = new AlertDialog.Builder(context).setTitle("选择仓库")
                        .setItems(s, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                //tvxj.setText(s[which]);
//                                list.get(p).setCk(s[which]);
//                                notifyDataSetChanged();
                                ckid = listCK.get(which).getFItemID();
                                ckname = listCK.get(which).getFName();
                                v.setText(ckname);
                            }
                        }).create();
                ad.show();
            }
//

//            list.clear();
//            adapter.notifyDataSetChanged();
        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
    public void testConnection4(Connection con) throws java.sql.SQLException {
        CallableStatement callStmt = null;
        CallableStatement callStmt2 = null;
        try {
            listCK.clear();
            //
            String sql = "select * from t_Stock";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                CK entity = new CK();
                entity.setFItemID(rs.getString("FItemID"));
                entity.setFName(rs.getString("FName"));

                listCK.add(entity);


            }


            rs.close();
            stmt.close();


        } catch (SQLException e) {


        } finally {
            if (null != callStmt) {
                callStmt.close();
                callStmt2.close();
            }
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
    public void onEventMainThread(RukuEntity e) {

        double t = e.getNumber();

        total -= t;

        tvnumber.setText(total + "");

    }

}
